package com.eurasia.assignment.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eurasia.assignment.domain.Role;
import com.eurasia.assignment.domain.User;
import com.eurasia.assignment.security.JwtTokenUtil;
import com.eurasia.assignment.service.UserService;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final JwtTokenUtil jwtTokenUtil;
    private final UserService userService;

    public AuthController(JwtTokenUtil jwtTokenUtil, UserService userService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        
        if (userService.validateUser(username, password)) {
            Optional<User> userOpt = userService.findByUsername(username);
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                // 从用户对象中获取角色列表
                var roles = user.getRoles().stream()
                        .map(Role::getName)
                        .collect(Collectors.toList());
                
                String token = jwtTokenUtil.generateToken(username, roles);
                
                Map<String, String> response = new HashMap<>();
                response.put("token", token);
                response.put("type", "Bearer");
                response.put("message", "登录成功！测试时请在请求头中添加：Authorization: Bearer " + token);
                
                return ResponseEntity.ok(response);
            }
        }
        
        Map<String, String> response = new HashMap<>();
        response.put("message", "用户名或密码错误");
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
    }

    //用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            User registeredUser = userService.registerUser(user);
            Map<String, String> response = new HashMap<>();
            response.put("message", "注册成功");
            response.put("username", registeredUser.getUsername());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    //管理员注册
    @PostMapping("/register/admin")
    public ResponseEntity<?> registerAdmin(@RequestBody Map<String, String> registerRequest) {
        try {
            // 从请求中提取用户信息和管理员注册码
            User user = new User();
            user.setUsername(registerRequest.get("username"));
            user.setPassword(registerRequest.get("password"));
            user.setEmail(registerRequest.get("email"));
            
            String adminCode = registerRequest.get("adminCode");// 管理员注册码
            
            User registeredUser = userService.registerAdminUser(user, adminCode);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "管理员注册成功");
            response.put("username", registeredUser.getUsername());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    //教师注册
    @PostMapping("/register/teacher")
    public ResponseEntity<?> registerTeacher(@RequestBody Map<String, String> registerRequest) {
        try {
            // 从请求中提取用户信息和教师注册码
            User user = new User();
            user.setUsername(registerRequest.get("username"));
            user.setPassword(registerRequest.get("password"));
            user.setEmail(registerRequest.get("email"));
            
            String teacherCode = registerRequest.get("teacherCode");// 教师注册码
            
            User registeredUser = userService.registerTeacherUser(user, teacherCode);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "教师注册成功");
            response.put("username", registeredUser.getUsername());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}